//
// Created by wty on 22-7-21.
//
#include"sylar/http/http_connection.h"
#include"sylar/log.h"
#include"sylar/iomanager.h"
#include<iostream>

static sylar::Logger::ptr logger = SYLAR_LOG_ROOT();

void test_pool(){
    sylar::http::HttpConnectionPool::ptr pool(new sylar::http::HttpConnectionPool(
            "www.sylar.top", "", 80, false, 10, 1000*30, 20));
    sylar::IOManager::GetThis()->addTimer(100, [pool](){
        auto r = pool->doGet("/", 300);
        SYLAR_LOG_INFO(logger)<<r->toString();
    });

}


void run() {
    sylar::Address::ptr addr = sylar::Address::LookupAnyIPAddress("www.sylar.top:80");
    if (!addr) {
        SYLAR_LOG_INFO(logger) << " get addr error";
        return;
    }
    sylar::Socket::ptr sock = sylar::Socket::CreateTCPSocket();
    bool rt = sock->connect(addr);
    if (!rt) {
        SYLAR_LOG_INFO(logger) << " connect " << *addr << " failed";
        return;
    }
    sylar::http::HttpConnection::ptr conn(new sylar::http::HttpConnection(sock));
    sylar::http::HttpRequest::ptr req(new sylar::http::HttpRequest);
    req->setPath("/blog/");
    req->setHeader("host", "www.sylar.top");
    SYLAR_LOG_INFO(logger) << "req:" << std::endl << *req;

    conn->sendRequest(req);
    auto rsp = conn->recvResponse();
    if (!rsp) {
        SYLAR_LOG_INFO(logger) << " recv reponse error";
        return;
    }
    SYLAR_LOG_INFO(logger) << "rsp:" << std::endl << *rsp;

    std::ofstream ofs("rsp.dat");
    ofs << *rsp;
    SYLAR_LOG_INFO(logger) << "==================";

    auto http_con = sylar::http::HttpConnection::DoGet("http://www.sylar.top/", 300);
    SYLAR_LOG_INFO(logger) << " result:" << http_con->result << " error=" << http_con->error << " rsp="
                           << (rsp ? rsp->toString() : "");

}


int main(int argc, char** argv){
    sylar::IOManager iom(2);
    iom.schedule(test_pool);
    return 0;
}